{% extends './management_base.html' %}

{% block title %} 后台登录 {% end %}

{% block main %}
<div class="page">
  <div class="page-single">
    <div class="container">
      <div class="row">
        <div class="col col-login mx-auto">
          <div class="text-center mb-6">
            <h1>Mason-BLOG</h1>
          </div>
          <form class="card dimmer">
            <div class="card-body p-6 dimmer-content">
              <div class="loader"></div>
              <div class="form-group">
                <label class="form-label">账号</label>
                <input type="text" class="form-control" name="username" placeholder="">
              </div>
              <div class="form-group">
                <label class="form-label">密码</label>
                <input type="password" class="form-control" name="password" placeholder="">
              </div>
              <div class="form-group">
                <label class="custom-control custom-checkbox">
                  <input type="checkbox" name="remember_me" class="custom-control-input" checked/>
                  <span class="custom-control-label">记住我</span>
                </label>
              </div>
              <div class="form-footer">
                <button type="button" class="btn btn-primary btn-block" id="sigin_button" onclick="sigin()">登录</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  require(["jquery"], function($){
    $("input[name=username]").val(window.localStorage.login_name)

    $("body").keyup(function(event){
      if(event.keyCode == 13){
        $("#sigin_button").click()
      }
    })
  })

  function sigin(){
    let usernameInput = $("input[name=username]").val()
    let passwordInput = $("input[name=password]").val()
    let remember = $("input[name=remember_me]").is(":checked")
    if (usernameInput == "" || passwordInput == ""){
      console.log("输入不能为空！")
      showAlert(status=0, msg="输入不能为空！")
      return false
    }
    console.log(`记住我：${remember}`)
    if (remember){
      window.localStorage.login_name = usernameInput
    }else{
      window.localStorage.login_name = ""
    }
    // 加载动画
    $(".dimmer").addClass("active")
    // 发起请求
    $.ajax("/author/login", {
      method: "POST",
      contentType: "application/json",
      dataType: "json",
      headers: {},
      data: JSON.stringify({
        username: usernameInput,
        password: passwordInput
      }),
    }).done(function(data){
      console.log(data)
      if (data["status"]==1){
        showAlert(1, data["msg"])
        localStorage.userName = data["data"]["userName"]
        setTimeout(() => {
          console.log("跳转首页")
          location.href = data["data"]["href"]
        }, 1500);
      }else{
        showAlert(0, data["msg"])
        return false
      }
    }).fail(function(xhr, error){

    }).always(()=>{
      $(".dimmer").removeClass("active")
    })
  }

</script>
{% end %}